﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using WMS.HelperClasses;
using WHMS.HelperClasses;
using SD.LLBLGen.Pro.ORMSupportClasses;
using WHMS.EntityClasses;

namespace WMS
{
	public partial class SupplyOrderForm : Form
	{
		SupplyOrderEntity _currentOrder;
		DataMngrFormBase<SupplyOrderItemEntity> _orderItemsForm;
		List<ErrorProvider> _errorProviders;

		public SupplyOrderForm()
		{
			InitializeComponent();
            HideOrViewWeightCol();
		}

        private void HideOrViewWeightCol()
        {
            var weightCol = _transItemsGrid.Columns["Weight"];

            if (weightCol != null)
            {
                if (UserInfo.Roles.Where(r => r.ViewWorkshop == true).Count() > 0)
                {
                    weightCol.Visible = true;
                }
                else
                {
                    weightCol.Visible = false;
                }
            }
        }

		private void SupplyOrderForm_Load(object sender, EventArgs e)
		{
			_currentOrder = new SupplyOrderEntity();
			_errorProviders = new List<ErrorProvider>();

			LoadData();			

			InitializeDataSources();

		}

		private void RetrieveBtn_Click(object sender, EventArgs e)
		{
			if (string.IsNullOrEmpty(SupplyOrderNumberTB.Text.Trim()))
				return;

			var collection = new EntityCollection<SupplyOrderEntity>();

			var filter = new RelationPredicateBucket(SupplyOrderFields.SupplyOrderNumber == SupplyOrderNumberTB.Text.Trim());

			DALHelper.FetchCollection(collection, filter);

			if (collection.Count <= 0)
			{
				InitializeDataSources();
				return;
			}

			_currentOrder = collection[0];
			BindDataSources();
            var projectfilter = new RelationPredicateBucket(ProjectFields.Id == collection[0].ProjectId);
            EntityCollection<ProjectEntity> project = new EntityCollection<ProjectEntity>();
            DALHelper.FetchCollection(project, projectfilter);
            ProjectsTB.Text = project[0].Code;

            var supplierCollection = new EntityCollection<SupplierEntity>();
            var supplierFilter = new RelationPredicateBucket(SupplierFields.Id == collection[0].SupplierId);
            DALHelper.FetchCollection(supplierCollection, supplierFilter);
            SupplierTB.Text = supplierCollection[0].Code;




			_supplyOrderItems.Clear();
			DALHelper.FetchCollection(_supplyOrderItems, new RelationPredicateBucket(SupplyOrderItemFields.SupplyOrderId == _currentOrder.Id));

            //Fill ItemName & ItemCode columns in retrieving order 
            if (_transItemsGrid.Rows.Count > 0)
            {
                for (int currentRow = 0; currentRow < _transItemsGrid.Rows.Count - 1; currentRow++)
                {
                    _transItemsGrid.Rows[currentRow].Cells[SequenceColumn.Index].Value = currentRow + 1;

                    int productItemId = Int32.Parse(_transItemsGrid.Rows[currentRow].Cells[ItemIdColumn.Index].Value.ToString());
                    GetItemDetailsByItemId(currentRow, productItemId);
                }

            }

            if (_supplyOrderItems != null)
            {
                foreach (var transItem in _supplyOrderItems)
                {
                    var itemCollection = new EntityCollection<ItemEntity>();

                    int itemId = ((SupplyOrderItemEntity)(transItem)).ItemId;

                    var itemFilter = new RelationPredicateBucket(ItemFields.Id == itemId);

                    DALHelper.FetchCollection(itemCollection, itemFilter);

                    if (itemCollection.Count > 0)
                    {
                        ((SupplyOrderItemEntity)(transItem)).Item = itemCollection[0];
                    }
                }
            }

			ValidateOrderNumber();



			EnableDisableControls();
		}

		private void NewBtn_Click(object sender, EventArgs e)
		{
			InitializeDataSources();
            ProjectsTB.Text = string.Empty;
            SupplierTB.Text = string.Empty;
			ResetTransactionItems();
		}

        //private void ProjectsDDL_SelectedIndexChanged(object sender, EventArgs e)
        //{
        //    var projectId = 0;

        //    if (ProjectsDDL.SelectedItem != null)
        //    {
        //        projectId = (int)((System.Data.DataRowView)(ProjectsDDL.SelectedItem)).Row.ItemArray[0];
        //    }

        //    Business.GetSupplyOrderItemsPlannedForProject(projectId, _items);

        //    var filter = new RelationPredicateBucket();
        //    filter.PredicateExpression.Add(new FieldCompareSetPredicate(ContractorFields.Id, null, ProjectContractorFields.ContractorId, null, SetOperator.In, new PredicateExpression(ProjectContractorFields.ProjectId == projectId)));			

        //    ResetTransactionItems();

        //    EnableDisableControls();

        //}

		private void SaveBtn_Click(object sender, EventArgs e)
		{
			if (!ValidateForm())
				return;

            //*************************************
            // 3agn el sneeeeeeeeeeeeen 
            //*************************************
            //if (!_currentOrder.IsNew)
            //{
            //    if ((bool)DALHelper.GetValue(SupplyOrderFields.IsProcessed, SupplyOrderFields.Id, _currentOrder.Id))
            //    {
            //        RetrieveOrder();
            //        return;
            //    }
            //}

			_currentOrder.CreatedBy = UserInfo.UserId;
            _currentOrder.ProjectId = GetSelectedProjectId();
            _currentOrder.SupplierId = GetSelectedSupplierId();

			foreach (SupplyOrderItemEntity item in _supplyOrderItems)
			{
                
				_currentOrder.SupplyOrderItems.Add(item);
			}

			DALHelper.DeleteCollection(_supplyOrderItems.RemovedEntitiesTracker);
			if (DALHelper.SaveEntity(_currentOrder, true))
			{
				RetrieveOrder();
				MessageBox.Show("تم الحفظ بنجاح.");
			}
		}

		private void TextBox_KeyPress(object sender, KeyPressEventArgs e)
		{
			//e.Handled = FormsHelper.IsNumericCharachter(e.KeyChar);
			FormsHelper.HandleNumericTextBoxKeypress(sender, e);
		}

		private void TotalTB_TextChanged(object sender, EventArgs e)
		{
			UpdateTotalEGP();
			UpdateTotalAfterDiscount();
		}

		private void TotalAfterDiscountTB_TextChanged(object sender, EventArgs e)
		{
			UpdateTotalAfterDiscountEGP();
		}

		private void CurrencyCoeffTB_TextChanged(object sender, EventArgs e)
		{
			UpdateTotalEGP();
			UpdateTotalAfterDiscountEGP();
		}

		private void DiscountTB_TextChanged(object sender, EventArgs e)
		{
			UpdateTotalAfterDiscount();
		}

		private void OtherDiscountTB_TextChanged(object sender, EventArgs e)
		{
			UpdateTotalAfterDiscount();
		}

		private void _transItemsGrid_CellValueChanged(object sender, DataGridViewCellEventArgs e)
		{
			if (e.RowIndex < 0)
				return;
            

			var priceCell = _transItemsGrid.Rows[e.RowIndex].Cells[unitPriceDataGridViewTextBoxColumn.Index];
			var discountCell = _transItemsGrid.Rows[e.RowIndex].Cells[unitDiscountDataGridViewTextBoxColumn.Index];
			var costCell = _transItemsGrid.Rows[e.RowIndex].Cells[unitCostDataGridViewTextBoxColumn.Index];

			if (e.ColumnIndex == unitPriceDataGridViewTextBoxColumn.Index
				|| e.ColumnIndex == unitDiscountDataGridViewTextBoxColumn.Index)
			{ 
				decimal price = 0;
				decimal discount = 0;

				if(decimal.TryParse(priceCell.Value.ToString(), out price) && decimal.TryParse(discountCell.Value.ToString(), out discount))
				{
					costCell.Value = price * (100 - discount) / 100;
				}
			}
		}


		void LoadData()
		{
            //FormsHelper.LoadComboBox(ProjectsDDL, ProjectFields.Id, ProjectFields.Name, () => Business.GetRunningAndGeneralProjects());
            //FormsHelper.LoadComboBox(SupplierDDL, SupplierFields.Id, SupplierFields.Name, (x, y) => DALHelper.GetDynamicList(x, y, null));
			FormsHelper.LoadComboBox(CurrencyDDL, CurrencyFields.Id, CurrencyFields.Name, (x, y) => DALHelper.GetDynamicList(x, y, null, new SortExpression(CurrencyFields.Order | SortOperator.Ascending)));			

            //FormsHelper.CheckProjects(ProjectsDDL.Items, new List<Control>() { _transItemsGrid, SaveBtn, bindingNavigator1 }, NoProjectsLbl);

            
		}

		private void InitializeDataSources()
		{
			_currentOrder = new SupplyOrderEntity();
			_supplyOrderItems.RemovedEntitiesTracker = new EntityCollection<SupplyOrderItemEntity>();

			BindDataSources();

			EnableDisableControls();
		
			_currentOrder.CurrencyId = 23;
			_currentOrder.CurrencyRate = 1;


			//if (CurrencyDDL.Items.Count > 0)
			//{
			//    CurrencyDDL.SelectedIndex = 0;
			//    CurrencyDDL.SelectedValue = 1;
			//}
		}

		private void BindDataSources()
		{
			_supplyOrderBS.DataSource = _currentOrder;
		}

		void EnableDisableControls()
		{
			var enabled = (!_currentOrder.IsProcessed && GetSelectedProjectId() > 0);
            _transItemsGrid.Enabled = true; // 3agn el sneeeeeeeeeeeen
			SaveBtn.Enabled = true; // 3agn el sneeeeeeeeeeeen 
            bindingNavigatorDeleteItem.Enabled = enabled; // 3agn el sneeeeeeeeeeeen
            bindingNavigatorAddNewItem.Enabled = true; // 3agn el sneeeeeeeeeeeen 
			//bindingNavigator1.Enabled = enabled;
			_alreadyApprovedLbl.Visible = _currentOrder.IsProcessed;

			ProjectsTB.Enabled = _currentOrder.IsNew;
			NewBtn.Enabled = !_currentOrder.IsNew;
			DeleteBtn.Enabled = !(_currentOrder.IsNew || _currentOrder.IsProcessed);
		}

		private int GetSelectedProjectId()
		{
                if (String.IsNullOrEmpty(ProjectsTB.Text))
				return 0;

                int projectid = 0;

                ProjectEntity project = Business.GetProjectByCode(ProjectsTB.Text);
                if (project!=null)
                return project.Id;

                return projectid;
		}

        private int GetSelectedSupplierId()
        {
            if (String.IsNullOrEmpty(SupplierTB.Text))
                return 0;

            DataTable Supplier = Business.GetSupplierDetails(SupplierTB.Text);

            int supplierid = 0;
            if (Supplier.Rows.Count > 0)
                supplierid=Int32.Parse(Supplier.Rows[0][0].ToString());

            return supplierid;
        
        }

		private void ResetTransactionItems()
		{
			if (_orderItemsForm != null)
			{
				_orderItemsForm.Dispose();
				_orderItemsForm = null;
			}

			var label = new Label();
			_orderItemsForm = new DataMngrFormBase<SupplyOrderItemEntity>(_supplyOrderItems, _transItemsGrid, _itemsBS, new Button(), label, label, new RelationPredicateBucket(SupplyOrderItemFields.SupplyOrderId == 0));

           
            
            _orderItemsForm.SetNumericFields(new List<int> { 1, 2 });
			_orderItemsForm.SetMandatoryFields(new List<int>() { 0, 1, 2 });
		}


		private void RetrieveOrder()
		{
			if (string.IsNullOrEmpty(SupplyOrderNumberTB.Text.Trim()))
				return;

			var collection = new EntityCollection<SupplyOrderEntity>();
            var filter = new RelationPredicateBucket(SupplyOrderFields.SupplyOrderNumber == SupplyOrderNumberTB.Text.Trim());
            //filter.Relations.Add(SupplyOrderEntity.Relations.ProjectEntityUsingProjectId);

			DALHelper.FetchCollection(collection, filter);
			if (collection.Count <= 0)
			{
				InitializeDataSources();
				return;
			}

            var supplierCollection = new EntityCollection<SupplierEntity>();
            var supplierFilter = new RelationPredicateBucket(SupplierFields.Id == collection[0].SupplierId);
            DALHelper.FetchCollection(supplierCollection, supplierFilter);
            SupplierTB.Text = supplierCollection[0].Code;

            var projectfilter = new RelationPredicateBucket(ProjectFields.Id == collection[0].ProjectId);
            EntityCollection<ProjectEntity> project = new EntityCollection<ProjectEntity>();
            DALHelper.FetchCollection(project, projectfilter);
            ProjectsTB.Text = project[0].Code;
            
			_currentOrder = collection[0];
			BindDataSources();

			_supplyOrderItems.Clear();
			DALHelper.FetchCollection(_supplyOrderItems, new RelationPredicateBucket(SupplyOrderItemFields.SupplyOrderId == _currentOrder.Id));

            //Fill ItemName & ItemCode columns in retrieving order 
            if (_transItemsGrid.Rows.Count > 0)
            {
                for (int currentRow = 0; currentRow < _transItemsGrid.Rows.Count-1; currentRow++)
                {
                    _transItemsGrid.Rows[currentRow].Cells[SequenceColumn.Index].Value = currentRow+1;
                    int productItemId = Int32.Parse(_transItemsGrid.Rows[currentRow].Cells[ItemIdColumn.Index].Value.ToString());
                    GetItemDetailsByItemId(currentRow, productItemId);
                }

            }

            if (_supplyOrderItems != null)
            {
                foreach (var transItem in _supplyOrderItems)
                {
                    var itemCollection = new EntityCollection<ItemEntity>();

                    int itemId = ((SupplyOrderItemEntity)(transItem)).ItemId;

                    var itemFilter = new RelationPredicateBucket(ItemFields.Id == itemId);

                    DALHelper.FetchCollection(itemCollection, itemFilter);

                    if (itemCollection.Count > 0)
                    {
                        ((SupplyOrderItemEntity)(transItem)).Item = itemCollection[0];
                    }
                }
            }

            ValidateOrderNumber();

			EnableDisableControls();
		}

		private bool ValidateOrderNumber()
		{
			if (!string.IsNullOrEmpty(SupplyOrderNumberTB.Text.Trim()))
			{
				if (Business.CheckExisitngSupplyOrderNumber(SupplyOrderNumberTB.Text.Trim(), _currentOrder.Id))
				{
					var errorProvider = new ErrorProvider(this);
					_errorProviders.Add(errorProvider);

					errorProvider.SetError(SupplyOrderNumberTB, "رقم الطلب مستخدم");
					errorProvider.RightToLeft = true;
					return false;
				}
				else
				{
					foreach (var errorProvider in _errorProviders)
					{
						if (!string.IsNullOrEmpty(errorProvider.GetError(SupplyOrderNumberTB)))
						{
							errorProvider.SetError(SupplyOrderNumberTB, string.Empty);
						}
					}
				}
			}
			return true;
		}

		private bool ValidateForm()
		{
			var isValid = true;

			var controls = new List<Control>();
			controls.Add(SupplyOrderNumberTB);
			controls.Add(ProjectsTB);
            //controls.Add(SupplierDDL);
            controls.Add(SupplierTB);

			if (_errorProviders == null)
			{
				_errorProviders = new List<ErrorProvider>();
			}
			else
			{
				foreach (var errorProvider in _errorProviders)
				{
					errorProvider.Clear();
					errorProvider.Dispose();
				}
			}
			foreach (var control in controls)
			{
				if (string.IsNullOrEmpty(control.Text.Trim()))
				//(control is TextBox && string.IsNullOrEmpty(control.Text.Trim()))
				//|| (control is ComboBox && control.Text)
				//)
				{
					var errorProvider = new ErrorProvider(this);
					_errorProviders.Add(errorProvider);

					errorProvider.SetError(control, "يجب إدخال قيمة");
					errorProvider.RightToLeft = true;

					isValid = false;
					continue;
				}
			}

            if (GetSelectedSupplierId() == 0)
            {
                var errorProvider = new ErrorProvider(this);
                _errorProviders.Add(errorProvider);

                errorProvider.SetError(SupplierTB, "يجب إدخال قيمة صحيحة");
                errorProvider.RightToLeft = true;

                isValid = false;
            }

            if (GetSelectedProjectId() == 0)
            {
                var errorProvider = new ErrorProvider(this);
                _errorProviders.Add(errorProvider);

                errorProvider.SetError(ProjectsTB, "يجب إدخال قيمة صحيحة");
                errorProvider.RightToLeft = true;

                isValid = false;
            }
			if (!ValidateOrderNumber())
				isValid = false;

            if (_orderItemsForm!=null)
			if (!_orderItemsForm.IsDataValid())
				isValid = false;

			if (_supplyOrderItems.Count <= 0)
			{
				isValid = false;
				MessageBox.Show("يجب إضافة أصناف", "خطأ فى الحفظ", MessageBoxButtons.OK, MessageBoxIcon.Error);
			}

			return isValid;
		}

		private void _transItemsGrid_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
		{
			//Open the search form for products using code or name 
            if (e.ColumnIndex == ItemCodeColumn.Index)
            {
                 var itemPickerForm = new ItemPickerForm(1);
                 if (itemPickerForm.ShowDialog() == DialogResult.OK)
                {
                    GetItemDetailsByItemId(e.RowIndex, itemPickerForm.SelectedItemId);
                                     
                }
            }

            else if (e.ColumnIndex == quantityDataGridViewTextBoxColumn.Index)
            {

                var itemIdValue = _transItemsGrid.Rows[e.RowIndex].Cells[ItemIdColumn.Index].Value;
                if (itemIdValue == null)
                    return;

                var form = new UnitConverterForm((int)itemIdValue);
                if (form.ShowDialog() == DialogResult.OK)
                {
                    _transItemsGrid.SuspendLayout();
                    _transItemsGrid.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = form.Value;
                    _transItemsGrid.UpdateCellValue(e.ColumnIndex, e.RowIndex);
                    _transItemsGrid.ResumeLayout(true);
                }
            }
		}

		private void UpdateTotalEGP()
		{
			decimal value = 0;
			if (decimal.TryParse(TotalTB.Text, out value))
			{
				decimal currencyRate = 0;
				decimal.TryParse(CurrencyCoeffTB.Text, out currencyRate);

				TotalEGPTB.Text = (value * currencyRate).ToString();
			}
		}
		private void UpdateTotalAfterDiscountEGP()
		{
			decimal value = 0;
			if (decimal.TryParse(TotalAfterDiscountTB.Text, out value))
			{
				decimal currencyRate = 0;
				decimal.TryParse(CurrencyCoeffTB.Text, out currencyRate);

				TotalAfterDiscountEGPTB.Text = (value * currencyRate).ToString();
			}
		}
		private void UpdateTotalAfterDiscount()
		{
			decimal valueAfterDiscount = 0;
			decimal value = 0;
			if (decimal.TryParse(TotalTB.Text, out value))
			{
				valueAfterDiscount = value;

				decimal discountRate = 0;
				if (decimal.TryParse(DiscountTB.Text, out discountRate))
				{
					valueAfterDiscount = valueAfterDiscount * (1 - (discountRate / 100));	
				}

				decimal otherDiscount = 0;
				if (decimal.TryParse(OtherDiscountTB.Text, out otherDiscount))
				{
					valueAfterDiscount = valueAfterDiscount - otherDiscount;
				}				
			}

			TotalAfterDiscountTB.Text = valueAfterDiscount.ToString();
		}

		private void SearchBtn_Click(object sender, EventArgs e)
		{
			var filter = new RelationPredicateBucket();
			filter.Relations.Add(SupplyOrderEntity.Relations.ProjectEntityUsingProjectId);

			var searchForm = new SearchSupplyOrderForm(SupplyOrderFields.SupplyOrderNumber, SupplyOrderFields.ProjectId, SupplyOrderFields.Date, filter, null);
			if (searchForm.ShowDialog() == DialogResult.OK)
			{
                SupplyOrderNumberTB.Text = searchForm.SelectedNumber;
				RetrieveOrder();
			}
		}

		private void DeleteBtn_Click(object sender, EventArgs e)
		{
			var form = new DeleteConfirmationForm();

			if (form.ShowDialog() == DialogResult.Yes)
			{
				if (DALHelper.DeleteEntity(_currentOrder))
				{
					InitializeDataSources();
					ResetTransactionItems();
				}
			}
		}

        /// <summary>
        /// Retrieve the data table represent item(Product) details based on ItemId
        /// Added by Thabet
        /// </summary>
        /// <param name="rowIndex"> Index of row in data grid</param>
        /// <param name="itemId">The ID of item(Product)</param>
        private void GetItemDetailsByItemId(int rowIndex, int itemId)
        {
            DataTable itemDT = Business.GetItemDetails(itemId);
            if (itemDT.Rows.Count <= 0)
                return;

            _transItemsGrid.Rows[rowIndex].Cells[ItemCodeColumn.Index].Value =itemDT.Rows[0][0].ToString();
            _transItemsGrid.Rows[rowIndex].Cells[ItemNameColumn.Index].Value = itemDT.Rows[0][1].ToString();

            _transItemsGrid.Rows[rowIndex].Cells[ItemIdColumn.Index].Value = itemId;
            
            return;
        }
        /// <summary>
        /// Retrieve the data table represent item(Product) details based on ItemCode
        /// Added by Thabet
        /// </summary>
        /// <param name="rowIndex">Index of row in data grid</param>
        /// <param name="itemCode">The code of item</param>
        private void GetItemDetailsByItemCode(int rowIndex, string itemCode)
        {
            var dt = Business.GetItemDetails(itemCode, 1);
            if (dt.Rows.Count <= 0)
                return;

           _transItemsGrid.Rows[rowIndex].Cells[ItemIdColumn.Index].Value = dt.Rows[0][0].ToString();
            _transItemsGrid.Rows[rowIndex].Cells[ItemNameColumn.Index].Value = (string)dt.Rows[0][1].ToString();
           
            return;
        }

        private void _transItemsGrid_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex < 0)
                return;

            if ((e.ColumnIndex == ItemCodeColumn.Index)&&(_transItemsGrid.Rows[e.RowIndex].Cells[ItemCodeColumn.Index].Value !=null))
            {
                string productItemCode= _transItemsGrid.Rows[e.RowIndex].Cells[ItemCodeColumn.Index].Value.ToString();
                GetItemDetailsByItemCode(e.RowIndex, productItemCode);
            }
            else if (e.ColumnIndex == quantityDataGridViewTextBoxColumn.Index)
            {
                var itemCollection = new EntityCollection<ItemEntity>();

                var itemId = ((SupplyOrderItemEntity)(_supplyOrderItems[e.RowIndex])).ItemId;

                var itemFilter = new RelationPredicateBucket(ItemFields.Id == itemId);

                DALHelper.FetchCollection(itemCollection, itemFilter);

                if (itemCollection.Count > 0)
                {
                    ((SupplyOrderItemEntity)(_supplyOrderItems[e.RowIndex])).Item = itemCollection[0];
                }
            }
        }

        private void _transItemsGrid_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
        {

            _transItemsGrid.Rows[e.RowIndex].Cells[SequenceColumn.Index].Value = e.RowIndex+1;
        }

        private void btnShowReport_Click(object sender, EventArgs e)
        {
            List<SupplyOrderItemEntity> supplyOrderItems = new List<SupplyOrderItemEntity>();
            //List<SupplyOrderItemEntity> orderItems = ((SD.LLBLGen.Pro.ORMSupportClasses.CollectionCore<SD.LLBLGen.Pro.ORMSupportClasses.EntityBase2>)(_supplyOrderItems)).Items.ToList();
            foreach (var item in _supplyOrderItems.Items)
            {
                SupplyOrderItemEntity supplyOrderItem = new SupplyOrderItemEntity();
                supplyOrderItem.Id = ((SupplyOrderItemEntity)item).Id;
                supplyOrderItem.Quantity = ((SupplyOrderItemEntity)item).Quantity;
                supplyOrderItem.UnitPrice = ((SupplyOrderItemEntity)item).UnitPrice;
                supplyOrderItem.ItemId = ((SupplyOrderItemEntity)item).ItemId;

                supplyOrderItems.Add(supplyOrderItem);
            }
            WMS.Reports.SupplyOrderReportForm supplyOrderForm = new Reports.SupplyOrderReportForm(_currentOrder,supplyOrderItems);
            supplyOrderForm.ShowDialog();
        }

        private void ProjectsTB_TextChanged(object sender, EventArgs e)
        {
            if (!String.IsNullOrEmpty(ProjectsTB.Text))
            {
                ProjectEntity project =  Business.GetProjectByCode(ProjectsTB.Text.ToString());

                if (project != null)
                {
                    lblProjectName.Text = project.Name;
                    ProjectsTB.Text = project.Code;
                    EnableDisableControls();
                    Business.GetSupplyOrderItemsPlannedForProject(project.Id, _items);
                    var filter = new RelationPredicateBucket();
                    filter.PredicateExpression.Add(new FieldCompareSetPredicate(ContractorFields.Id, null, ProjectContractorFields.ContractorId, null, SetOperator.In, new PredicateExpression(ProjectContractorFields.ProjectId == project.Id)));
                    ResetTransactionItems();
                    EnableDisableControls();
                }
                else
                {
                    lblProjectName.Text = string.Empty;
                }
            }
            else
            {
                lblProjectName.Text = string.Empty;
                //RunBtn.Enabled = false;
            }
        }

        private void SupplierTB_TextChanged(object sender, EventArgs e)
        {
            if (!String.IsNullOrEmpty(SupplierTB.Text))
            {
                DataTable supplierDT = Business.GetSupplierDetails(SupplierTB.Text.ToString());

                if (supplierDT != null && supplierDT.Rows.Count > 0)
                {
                    lblSupplier.Text = supplierDT.Rows[0]["Name"].ToString();
                    EnableDisableControls();
                }
                else
                {
                    lblSupplier.Text = string.Empty;
                }
            }
            else
            {
                lblSupplier.Text = string.Empty;
            }
        }

        private void SearchProjectBtn_Click(object sender, EventArgs e)
        {
            ResetTransactionItems();
            var filter = new RelationPredicateBucket(ProjectFields.Status == "جارى");
            filter.PredicateExpression.AddWithOr(ProjectFields.IsGeneral == true);
            var searchForm = new SearchForm(ProjectFields.Code, ProjectFields.Name, ProjectFields.ActualStartDate, filter,
                                            () => Business.GetRunningAndGeneralProjects());
            if (searchForm.ShowDialog() == DialogResult.OK)
            {
                ProjectsTB.Text = searchForm.SelectedNumber;

                EnableDisableControls();
            }
        }

        private void SearchSupplierBtn_Click(object sender, EventArgs e)
        {
            ResetTransactionItems();
            var filter = new RelationPredicateBucket();
            var searchForm = new fromGeneralEntityPicker("Supplier");
            if (searchForm.ShowDialog() == DialogResult.OK)
            {
                SupplierTB.Text = searchForm.SelectedItemCode;
                EnableDisableControls();
            }
        }
	}
}
